package com.zhixiang.wbl.visitor.fragement;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.soundcloud.android.crop.Crop;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.zhixiang.wbl.visitor.ActivityManager.ScreenManager;
import com.zhixiang.wbl.visitor.Constant.Constant;
import com.zhixiang.wbl.visitor.Helper.OkHttpHelper;
import com.zhixiang.wbl.visitor.LoginActivity;
import com.zhixiang.wbl.visitor.R;
import com.zhixiang.wbl.visitor.Utils.VisitorUtil;
import com.zhixiang.wbl.visitor.activity.ShowQRCodeActivity;
import com.zhixiang.wbl.visitor.model.login.RootLogin;
import com.zhixiang.wbl.visitor.model.login.Visitor;
import com.zhixiang.wbl.visitor.widget.MyPopupWindow;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by dongzhixiang on 16/5/17.
 */
public class MyFragment extends BaseFragment implements View.OnClickListener
{
    private final static String TAG = "MyFragment";

    @ViewInject(R.id.id_img_avtor)
    ImageView avatorImage;
    @ViewInject(R.id.id_img_erweima)
    ImageView erweimaImage;
    @ViewInject(R.id.id_tv_nickname)
    TextView nickText;
    @ViewInject(R.id.id_tv_sex)
    TextView sexText;
    @ViewInject(R.id.id_tv_userage)
    TextView ageText;
    @ViewInject(R.id.id_tv_name)
    TextView nameText;
    @ViewInject(R.id.id_tv_mobile)
    TextView mobileText;
    @ViewInject(R.id.id_btn_logoout)
    Button logooutButton;
    private View mainView;
    private OkHttpHelper httpHelper = OkHttpHelper.getInstance();

    private Visitor mVisitor = null;

    @Override
    public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        mainView=  inflater.inflate(R.layout.fragment_my_new, container, false);
        return  mainView;
    }

    @Override
    public void init()
    {
        mVisitor = VisitorUtil.getCurrentVisitor(getContext());
        avatorImage.setOnClickListener(this);
        erweimaImage.setOnClickListener(this);
        logooutButton.setOnClickListener(this);
       if (mVisitor!=null)
       {
          updateUI();
       }
    }
   /*
   * 更新UI
   * */
   private void updateUI()
   {
       //用户头像
       Picasso.with(getContext()).load(mVisitor.getPortrait()).into(avatorImage);

       //用户昵称
       nickText.setText(mVisitor.getUsername());
       //用户性别
       sexText.setText(mVisitor.getSex());
       //用户年龄
       ageText.setText(mVisitor.getAge());
       //用户名称
       nameText.setText(mVisitor.getName());
       //手机号
       mobileText.setText(mVisitor.getMobile());
   }
    private Uri photoUri = null;
    private static final int SELECT_PIC_BY_TACH_PHTO = 1;
    private static final int SELECT_PIC_BY_PICK_PHTO = 2;
    //private static final int IMAGE_CUTTING = 3;
    private static final String IMAGE_TEMP_NAME = "temp_crop_image.jpg";
    /*
    * 拍照获取图片
    * */
    private void takePhoto()
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机

        photoUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));
        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

        //直接使用，没有缩小
        startActivityForResult(intent, SELECT_PIC_BY_TACH_PHTO);
    }
    /*
    * 从相册取图片
    * */
    private void pickPhoto()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent,SELECT_PIC_BY_PICK_PHTO);
    }
   /*
   * 裁剪图片实现
   * */
    public void startPhotoZoom(Uri uri)
    {
        File f = new File(Environment.getExternalStorageDirectory(),IMAGE_TEMP_NAME);
        Uri outputUri = Uri.fromFile(f);
        Crop.of(uri,outputUri).asSquare().start(getContext(),this);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
      // super.onActivityResult(requestCode,resultCode,data);
        if (resultCode != Activity.RESULT_OK) return;
//        Log.e(TAG, "onActivityResult: code "+requestCode );
        switch ( requestCode )
        {
            case SELECT_PIC_BY_PICK_PHTO:
                startPhotoZoom(data.getData());
                break;
            case SELECT_PIC_BY_TACH_PHTO:
                if (photoUri!=null)
                {
                    startPhotoZoom(photoUri);
                }
                 else
                {
                    Log.e(TAG, "onActivityResult: "+"拍照出错" );
                }
                break;
            case Crop.REQUEST_CROP :

                File f = new File(Environment.getExternalStorageDirectory(),IMAGE_TEMP_NAME);
                uploadImageToServer(f.getPath());
                if (photoUri!=null)
                {
                    File originFile = new File(photoUri.getPath());
                    originFile.delete();
                }
                break;
        }
    }
//  /*
//  * 保存图片到指定文件夹的方法
//  * */
//    public String saveBitmap(Bitmap bm)
//    {
//        File f = new File(Environment.getExternalStorageDirectory(),IMAGE_TEMP_NAME);
//        if (f.exists())
//            f.delete();
//        try
//        {
//            FileOutputStream out = new FileOutputStream(f);
//            bm.compress(Bitmap.CompressFormat.JPEG,90,out);
//            out.flush();
//            out.close();
//        }
//        catch (FileNotFoundException e)
//        {
//
//        }catch (Exception e)
//        {
//            e.printStackTrace();
//        }
//       return f.getPath();
//    }
    /*
  * 上传图片到服务器
  * */

    private  void uploadImageToServer(final String filePath)
    {
                MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");
                File file = new File(filePath);
                String url = Constant.VISITOR_IMAGE_UPDATE;
                String userId = mVisitor.getId()+"";

                 RequestBody requestBody = new MultipartBuilder()
                        .type(MultipartBuilder.FORM)
                        .addFormDataPart("title", "logo")
                        .addFormDataPart("userId",userId)
                        .addFormDataPart("type","1")
                        .addFormDataPart("image", file.getName(),
                                RequestBody.create(MEDIA_TYPE_PNG, file))
                        .build();

                 Request request = new Request.Builder()
                        .header("Content-Type","multipart/form-data")
                        .url(url)
                        .post(requestBody)
                        .build();
                OkHttpClient client = new OkHttpClient();
                client.setWriteTimeout(10, TimeUnit.SECONDS);
                client.setReadTimeout(10,TimeUnit.SECONDS);
                client.setConnectTimeout(2,TimeUnit.SECONDS);
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        Log.e(TAG, "上传图片文件失败onFailure: "+e.toString() );
                    }

                    @Override
                    public void onResponse(Response response) throws IOException
                    {
                        if (response.isSuccessful())
                        {
                             try {
                                 String json = response.body().string();
                                 Log.e(TAG, "onResponse: "+json);
                                 parseDateFromServer(json);
                             }catch (Exception e)
                             {
                                 e.printStackTrace();
                             }
                        }
                    }
                });
    }
    /*
    * 解析Json数据
    * */
    public void parseDateFromServer(String jsonString)
    {
        Gson gson = new Gson();
        RootLogin data = gson.fromJson(jsonString, RootLogin.class);
       // Log.e(TAG, "parseDateFromServer:"+data.toString());
        if (data.getCode()==200)
        {
            mVisitor = data.getData();
            //缓存更新后的用户数据
            VisitorUtil.cacheVistorInfo(mVisitor,getContext());
            updateUIhander.sendEmptyMessage(UPDATE_UI);
        }
        else
        {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(),"用户信息更新失败",Toast.LENGTH_SHORT).show();
                }
            });

        }
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.id_img_avtor:
                avatorButtonClicked();
                break;
            case R.id.id_img_erweima:
                qrCodeButtonClicked();
                break;
            case R.id.id_btn_logoout:
                logoout();
                break;
        }
    }
    private MyPopupWindow myPopupWindow = null;
    /*
    * 设置图片点击事件
    * */
    public void avatorButtonClicked()
    {
        myPopupWindow = new MyPopupWindow(getContext(), new MyPopupWindow.OnPopWindowItemClickListener() {
            @Override
            public void onClick(int position)
            {
                switch (position)
                {
                    case 0:
                        if (myPopupWindow!=null)
                            myPopupWindow.dismiss();
                        takePhoto();

                        break;
                    case 1:
                        if (myPopupWindow!=null)
                            myPopupWindow.dismiss();
                        pickPhoto();

                        break;
                    case 2:
                        if (myPopupWindow!=null)
                            myPopupWindow.dismiss();
                        break;
                }
            }
        });
        myPopupWindow.showAtLocation(mainView, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0);
    }
    /*
    * 显示本人二维码点击事件
    * */
    public void qrCodeButtonClicked()
    {
        Intent intent = new Intent(getContext(), ShowQRCodeActivity.class);
        startActivity(intent);
    }
    private static final int UPDATE_UI = 8;
    Handler updateUIhander = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            Log.e(TAG, "updateUI:"+mVisitor.getPortrait());
            if (msg.what==UPDATE_UI)
            {
              updateUI();
            }
        }
    };

    /*
    * 退出
    * */
    private void logoout()
    {
        ScreenManager.getScreenManager().popAllActivityExceptOne(LoginActivity.class);
    }

}
